package com.springboot.frame.excel.style;


import lombok.extern.slf4j.Slf4j;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author TaoYu KanYuXia
 */
@Slf4j
public class AnnotationResolver {

    /**
     * 解析注解排除方法集
     */
    private static final List<String> EXCLUDE_METHODS = Arrays
            .asList("equals", "toString", "hashCode", "annotationType");

    /**
     * 注解
     */
    private Annotation annotation;

    /**
     * 该注解解析后的结果
     */
    private Map<String, Object> results;

    AnnotationResolver(Annotation annotation) {
        this.annotation = annotation;
        init();
    }

    /**
     * 获取注解的值
     *
     * @param methodName 注解方法名称
     * @param <T>        值
     * @return 该注解方法名称对象的值
     */
    @SuppressWarnings("unchecked")
    <T> T resolve(String methodName) {
        return (T) results.get(methodName);
    }

    /**
     * 解析该注解的所有值
     */
    private void init() {
        results = new HashMap<>();
        for (Method method : annotation.getClass().getDeclaredMethods()) {
            String methodName = method.getName();
            try {
                if (!EXCLUDE_METHODS.contains(methodName)) {
                    results.put(methodName, method.invoke(annotation));
                }
            } catch (ReflectiveOperationException e) {
                log.warn("Error to invoke  annotation {} of method {}", annotation.toString(), methodName);
            }
        }
    }

}
